# -*- coding:utf-8 -*-

from typing import Callable
from fastapi import FastAPI
from fastapp.database.mysql import register_mysql
from fastapp.database.redis import sys_cache, code_cache
from aioredis import Redis
import os
from loguru import logger
from fastapp.core.register import init_logging, register_middlewares, register_routers


def startup(app: FastAPI) -> Callable:
    """
    FastApi 启动完成事件
    :param app: FastAPI
    :return: start_app
    """
    async def app_start() -> None:
        # APP启动完成后触发
        print("fastapi已启动")
        # 注册数据库
        await register_mysql(app)
        # 注入缓存到app state
        app.state.cache = await sys_cache()
        app.state.code_cache = await code_cache()

        # OpenAI的key
        app.state.api_key = os.getenv("API_KEY")

        logger.info('=====初始化项目日志器======')
        init_logging()
        logger.info('logging is init success！！！')

        """注册中间件"""
        await register_middlewares(app)
        logger.info('middlewares is register success！！！')
        #
        # """注册路由"""
        # await register_routers(app)
        # logger.info('routers is register success！！！')

        pass
    return app_start


def stopping(app: FastAPI) -> Callable:
    """
    FastApi 停止事件
    :param app: FastAPI
    :return: stop_app
    """
    async def stop_app() -> None:
        # APP停止时触发
        print("fastapi已停止")
        cache: Redis = await app.state.cache
        code: Redis = await app.state.code_cache
        await cache.close()
        await code.close()

    return stop_app
